<template>
    <Header title="体检项管理"></Header>
    <div class="box">
        <div class="box-header">
            <span class="s1">数据筛选</span>
            <el-divider />
            <div>
                <span class="s2">输入查询：</span>
                <el-input v-model="query.projectid" placeholder="项目ID或项目名称" :clearable="true"/>
                <span class="s3">适用地区：</span>
                <div>
                    <div class="city-smallbox">
                        <el-select v-model="query.applicationarea" class="m-2" placeholder="全部" size="small"
                            @change="changeProvince" :clearable="true">
                            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                        </el-select>
                    </div>
                    <div class="city-smallbox2">
                        <el-select v-model="query.citys" class="m-2" placeholder="全部" size="small" :clearable="true">
                            <el-option v-for="item in option" :key="item.values" :labels="item.label"
                                :value="item.values" />
                        </el-select>
                    </div>
                </div>
                <div class="city-box">
                    <span class="s4">适用机构：</span>
                    <div class="city-smallbox3">
                        <el-select v-model="suitMechanism" class="m-2" placeholder="全部" size="small" :clearable="true">
                            <el-option v-for="item in mechanismOption" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </div>
                </div>
                <el-row class="mb-4">
                    <el-button type="primary" color="#0079fe" @click="readAll">查询</el-button>
                    <el-button @click="resetting">重置</el-button>
                </el-row>
            </div>
        </div>
        <div class="btn">
            <button props="addDisplay">
                <Add @addChange="updatePage" :addDisplay="true"></Add>
            </button>

            <button @click="showDel">
                删除
                <div class="dellist" v-show="isShow" ref="delManyOption">
                    <input type="button" value="已勾选数据" @click="delSelect" backgroundColor="gray" />
                    <input type="button" value="未勾选数据" @click="delNoselect" />
                </div>
            </button>
            <button>导入</button>
        </div>
        <div class="biaoge">
            <el-table :data="tableData" style="width:100%" @selection-change="handleSelectionChange" :border="true"
                :cell-style="{ 'text-align': 'center', 'font-size': '12px' }" :header-cell-style="{
                    'text-align': 'center', 'background-color': '#f9fafc',
                    'color': '#666'
                }">
                <el-table-column type="selection" min-width="53" />
                <el-table-column prop="id" label="项目ID" min-width="157" />
                <el-table-column prop="projectname" label="项目名称" min-width="179" />
                <el-table-column prop="originprice" label="原价" min-width="91" />
                <el-table-column prop="saleprice" label="售价" min-width="89" />
                <el-table-column prop="applicationarea" label="适用地区" min-width="223" />
                <el-table-column prop="isenable" label="是否启用" min-width="112">
                    <template #default="scope">{{ scope.row.isenable ? "启用" : "不启用" }}</template>
                </el-table-column>
                <el-table-column prop="ordernum" label="订购数量" min-width="93" />
                <el-table-column label="操作" min-width="179">
                    <template #default="scope">
                        <div class="delAndbianji">
                            <p class="s5" style="color:#1abc9c;padding-right: 10px;">
                                <Add @addChange="updatePage" :addDisplay="false" :testOptionId="scope.row.id"></Add>
                            </p>
                            <el-popconfirm title="您确认要删除嘛?" confirm-button-text="是" cancel-button-text="否"
                                @confirm="delClick(scope.row.id)">
                                <template #reference>
                                    <p style="color:#1abc9c;display: flex;align-items: center;">删除</p>
                                </template>
                            </el-popconfirm>

                        </div>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div>
            <div class="demo-pagination-block">
                <span class="page1">每页：</span>
                <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :default-page-size="10"
                    layout="sizes,slot, prev,pager,next,jumper" background :page-sizes="[10, 20, 30, 40, 50]" :total="total"
                    >
                    <template #default>
                        <span>共{{ pages }}页/{{ total }}条数据</span>
                    </template>
                </el-pagination>
            </div>
        </div>

    </div>
</template>

<script setup lang="ts">
import Header from '../../component/header.vue'
import { reactive, ref, watch } from 'vue'
import { ElTable, ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import service from '@/utils/service';
import Add from './add.vue'
import type { AxiosResponse } from 'axios';


const values = ref("")
//点击时显示
const isShow = ref(false)
const suitMechanism = ref("")
//分页
// 当前页
const currentPage = ref(1)
// 每页显示数据条数
const pageSize = ref(10)
// 总数据量
const total = ref(0)
//总共多少页
const pages = ref(parseInt(((total.value / pageSize.value) as unknown) as string) + 1)
//定义列表数据  
interface User {
    projectid?: string,
    projectname?: string,
    originprice?: number,
    saleprice?: number,
    applicationarea: string,
    isenable: boolean,
    ordernum: 0,
    id: number
}

const tableData = reactive<User[]>([])
//定义查询条件
interface ISearch {
    projectid?: string,
    id?: string,
    projectname?:string
    applicationarea?: string,
    citys?: string,
    _limit?: number,
    _page?: number,
}
//省份显示
interface Uorder {
    value: string,
    label: string
}
const options = reactive<Uorder[]>([])
const query = reactive<ISearch>({
    projectid: "",
    applicationarea: "",
    citys: "",
})
//精确搜索
const getDataByAnySituation = async (query:ISearch) => {
    let obj:ISearch = {}
    let regSearch = /^[A-Za-z0-9-]+$/
    if(query.projectid && regSearch.test(query.projectid as string)){
        obj.id = query.projectid 
    } 
    if (query.projectid && !regSearch.test(query.projectid as string)){
        obj.projectname = query.projectid
    }

    if(query.applicationarea){
        obj.applicationarea = query.applicationarea
    }
  
    if(query.citys){
        obj.citys = query.citys
    }
    await service({
        url:`/testOptions`,
        params:obj
    }).then(res=>{
        if(res.data){
            total.value = res.data.length
            obj._limit = pageSize.value
            obj._page = currentPage.value


        }
    })
    await service({
        url:`/testOptions`,
        params:obj
    }).then(res=>{
        if(res.data){
            tableData.length = 0;
            tableData.push(...res.data)    
        }
    })
}
watch([currentPage,pageSize],()=>{
    getDataByAnySituation(query)
    // console.log(currentPage.value,pageSize.value);
    
})


// 获取表格组件
// const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const multipleSelection = reactive<User[]>([])

// 获取选中行的数据
const handleSelectionChange = (val: User[]) => {
    multipleSelection.length = 0
    multipleSelection.push(...val)
}

getDataByAnySituation(query)

const readAll = () => {
    getDataByAnySituation(query)
}

//重置按钮
const resetting = () => {
    query.projectid = ""
    value.value = ""
    values.value = ""
    suitMechanism.value = ""
    getDataByAnySituation(query)
}
const value = ref('')
//省份显示
const getOptions = () => {
    service({
        url: '/provinceshx'
    }).then(res => {
        options.length = 0
        res.data.forEach((item: any) => {
            options.push({
                value: item.省,
                label: item.省
            })
        })
    })
}
getOptions()
//城市显示
interface Uorders {
    values: string,
    label: string
}
const option = reactive<Uorders[]>([])
const changeProvince = (val: string) => {
    // console.log("val", val);

    service({
        url: '/provinceshx',
        params: {
            省: val
        }
    }).then(res => {
        option.length = 0
        res.data[0].市.forEach((item: any) => {
            option.push({
                values: item.市名,
                label: item.市名
            })
        })
    })
}

const mechanismOption = [
    {
        value: '美年大健康',
        label: '美年大健康',
    },
    {
        value: '瑞慈',
        label: '瑞慈',
    },
    {
        value: '平安体检',
        label: '平安体检',
    },
    {
        value: '普惠体检',
        label: '普惠体检',
    }
]
//删除
//点击删除显示删除选项
const showDel = (e: MouseEvent) => {
    //阻止冒泡
    e.stopPropagation();
    ((delManyOption.value as unknown) as HTMLElement).style.top = `${e.offsetY}px`;
    ((delManyOption.value as unknown) as HTMLElement).style.left = `${e.offsetX}px`;
    // 显示删除选项框
    isShow.value = true
}
//隐藏删除选项框
document.onclick = () => {
    isShow.value = false
}
//删除多条选中数据
const delManyOption = ref(null)
const delSelect = () => {
    if (multipleSelection.length == 0) {
        ElMessageBox.alert('请先选择数据！', {
            confirmButtonText: '确认'
        }).catch(() => { })
    } else {
        ElMessageBox.confirm(
            '是否确定删除数据？',
            '警告',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
            .then(async () => {
                multipleSelection.forEach(item => {
                    service({
                        url: `/testOptions/${item.id}`,
                        method: "delete"
                    })
                })
                getDataByAnySituation(query)
                ElNotification({
                    title: '',
                    dangerouslyUseHTMLString: true,
                    message: '<img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" style="width:30px;height:30px;margin-right:5px;"/><strong>删除成功</strong>',
                })
            })
            .catch(() => {
                ElNotification({
                    title: '',
                    dangerouslyUseHTMLString: true,
                    message: '<img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" style="width:30x;height:30px;margin-right:5px;"/><strong>取消删除</strong>',
                })
            })
    }
}
// 删除未选中的数据
const delNoselect = async () => {
    if (multipleSelection.length === 0) {
        ElMessageBox.alert('请先选择数据！', {
            confirmButtonText: '确认'
        }).catch(() => { })
    } else {
        // 未选中的数据(获取未选中)
        let checkedKeys = <number[]>[]
        multipleSelection.forEach(item => {
            checkedKeys.length = 0
            checkedKeys.push(item.id)
        })
        let unselectedData = reactive<User[]>([])
        unselectedData.length = 0
        tableData.forEach(item => {
            if (!checkedKeys.includes(item.id)) {
                unselectedData.push({ ...item })
            }
        })
        ElMessageBox.confirm(
            '是否确定删除数据？',
            '警告',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
            .then(async () => {
                unselectedData.forEach(item => {
                    service({
                        url: `/testOptions/${item.id}`,
                        method: "delete"
                    }).then((res: AxiosResponse) => { })
                })

                getDataByAnySituation(query)
                ElNotification({
                    title: '',
                    dangerouslyUseHTMLString: true,
                    message: '<img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" style="width:30x;height:30px;margin-right:5px;"/><strong>删除成功</strong>',
                })

            })
            .catch(() => {
                ElNotification({
                    title: '',
                    dangerouslyUseHTMLString: true,
                    message: '<img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" style="width:30x;height:30px;margin-right:5px;"/><strong>取消删除</strong>',
                })
            })
    }
}

//确认删除单行数据
const delClick = async (id: number) => {
    let res = await service({
        url: `/testOptions/${id}`,
        method: 'delete'
    })
    if (res.data) {
        ElMessage({
            message: "删除成功！",
            type: "success"
        })
    }
    getDataByAnySituation(query)
}


const updatePage = () => {
    getDataByAnySituation(query)
}
</script>

<style scoped>
.box {
    width: 100%;
    height: 100%;
    background-color: #ffffff;
    margin: 10px 0 0 0;
}

.box-header {
    height: 130px;
    border: 1px solid #f1f1f1;
    margin: 0 10px 10px 7px;
    font-size: 14px;
}

.s1 {
    display: block;
    height: 28px;
    line-height: 49px;
    font-weight: 700;
    padding: 0 25px;

}

.el-input {
    width: 180px;
    height: 35px;
}

.s2 {
    padding-left: 40px;
}

.s3 {
    padding-left: 38px;

}

.s4 {
    margin: 20px;
}

.city-box {
    float: left;
    margin: -29px 626px;
}

.city-smallbox {
    width: 100px;
    height: 35px;
    border: 1px solid #f1f1f1;
    border-radius: 5px;
    float: left;
    margin: -34px 401px;
}

.city-smallbox2 {
    display: block;
    width: 100px;
    height: 35px;
    border: 1px solid #f1f1f1;
    border-radius: 5px;
    float: left;
    margin: -34px 510px;
}

.city-smallbox3 {
    display: block;
    width: 180px;
    height: 35px;
    border: 1px solid #f1f1f1;
    border-radius: 5px;
    float: left;
    margin: -23px 92px;
}

.el-select {
    border: 1px solid black;
    margin: 5px;
    border-radius: 5px;
}

.mb-4 {
    float: right;
}

.mb-4 .el-button {
    width: 80px;
    height: 35px;
    margin: -35px 10px;
}

.btn button {
    width: 81px;
    height: 30px;
    float: left;
    background-color: white;
    border: 1px solid #ccc;
    margin: 5px;
    position: relative;
}

.btn {
    margin-left: 15px;
    margin-bottom: 20px;
    height: 30px;
}

.biaoge {
    margin: 0 10px 10px 20px;

}

.el-table-column {
    color: #666666;
}

.el-table-column span {
    color: #aec29c;
}

.s5:hover {
    text-decoration: underline;
}

.delAndbianji {
    display: flex;
    justify-content: center;
}

.dellist {
    width: 88px;
    height: 63px;
    border: 1px solid rgb(93, 93, 93);
    border-radius: 2px;
    text-align: center;
    position: absolute;
    z-index: 999;
}

.dellist input {
    width: 77px;
    height: 23px;
    line-height: 23px;
    background-color: rgba(238, 234, 234, 0.742);
    border: 1px solid gray;
    border-radius: 2px;
    text-align: center;
    margin: 5px;
}

/* 分页 */
.demo-pagination-block+.demo-pagination-block {
    margin-top: 10px;
}

.demo-pagination-block .demonstration {
    margin-bottom: 16px;
}

.demo-pagination-block {
    display: flex;
    float: right;
}

.demo-pagination-block span {
    padding-left: 30px;
}

.page1 {
    font-size: 14px;
    padding-top: 8px;
}
</style>